<?php

namespace app\controller\merchant;

use app\BaseController;
use app\model\Plateform;
use think\facade\Cache;
use think\response\Json;

class User extends BaseController
{
    public function modify(): Json
    {
        $auth = getAuthorization();
        //获取账号信息
        $account = $this->app->make(Plateform::class)->where(['id' => $auth['id'], 'state' => 1, 'token' => $auth['token']])->find();
        if(empty($account)) throw new \Exception("登录已过期", 7004);
        //校验验证码是否正确
        $code = Cache::get('merchant_login_'.$account->mobile.'_code');
        if(empty($code) || $code != $this->request->post('code')) throw new \Exception("验证码错误", 70145);
        //判断是否和原密码一致
        if(checkPassword($this->request->post('password'), $account->encode, $account->password)) throw new \Exception("新密码不能与原密码一致", 70145);
        $password = setPassword($this->request->post('password'));
        $account->password = $password['password'];
        $account->encode = $password['encode'];
        $account->token = '';
        $account->save();
        Cache::delete('merchant_login_'.$account->mobile.'_code');
        return $this->success($account);
    }

    public function logout(): Json
    {
        $auth = getAuthorization();
        //获取账号信息
        $account = $this->app->make(Plateform::class)->where(['id' => $auth['id'], 'state' => 1, 'token' => $auth['token']])->find();
        if(empty($account)) throw new \Exception("登录已过期", 7004);
        $account->token = '';
        $account->save();
        return $this->success();
    }
}